<template>
  <div>
    <!-- pc端 -->
    <el-dialog v-model="outerVisible" :fullscreen="!infoWidth" :close-on-click-modal="false"
      :width="infoWidth ? '80%' : '100%'">
      <div class="common-layout">
        <el-container>
          <el-header style="height: 40px">
            <div class="mb-4 flex">
              <el-button type="primary" :disabled="setFilebut" @click="steFileinfo()">添加文件</el-button>
              <el-button type="success" :disabled="Savebut" @click="setwriteinfo()">保存内容</el-button>
            </div>
          </el-header>
          <el-divider />
          <!-- 导航栏 -->
          <el-container style="height: 600px" class="vuewrap">
            <el-scrollbar style="border-right: 1px solid #eee">
              <el-aside style="width: 300px">
                <el-tree highlight-current lazy :data="treeData" :height="208" :load="LazyLoadNode"
                  @current-change="treeCurrentChange">
                  <template #default="{ node }">
                    <span v-if="node.data.value.type == 'dir'" class="prefix" :class="{ 'is-leaf': node.isLeaf }">
                      <el-icon>
                        <Folder />
                      </el-icon>
                    </span>
                    <span v-if="node.data.value.type == 'file'" class="prefix" :class="{ 'is-leaf': node.isLeaf }">
                      <el-icon>
                        <Document />
                      </el-icon>
                    </span>
                    <span>{{ node.label }}</span>
                  </template>
                </el-tree>
              </el-aside>
            </el-scrollbar>
            <!-- web部分 -->
            <el-main v-show="showWeb" style="width: 350px">
              <WebCode ref="webinfo" />
            </el-main>
            <div v-show="!showWeb" style="
                width: 100%;
                height: 100%;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: space-evenly;
              ">
              <div>
                <imgfile :type="imgcont" />
              </div>
              <div>
                <el-button v-if="!Savebut" type="primary" @click.stop="onclickPreview">在线预览</el-button>
                <el-button v-if="!butjudgment" type="success" @click.stop="Compress">压缩文件</el-button>
                <el-button v-if="!Savebut" type="warning" @click.stop="httpfile">文件下载</el-button>
                <el-button v-if="!Savebut && imgcont == 'zip'" type="success" @click.stop="unzip">解压文件</el-button>
                <el-button v-if="!delBut" type="danger" @click="FileDel()">删除文件</el-button>
              </div>
            </div>
          </el-container>
        </el-container>
      </div>
    </el-dialog>
    <el-dialog v-model="setFile">
      <div class="Filebox">
        <el-text class="mx-1">文件类型</el-text>
        <el-radio-group v-model="radio" class="ml-4">
          <el-radio value="1" size="large">创建文件夹</el-radio>
          <el-radio value="2" size="large">创建文件</el-radio>
        </el-radio-group>
      </div>
      <div class="Filebox">
        <el-text class="mx-1">文件名称</el-text>
        <el-input v-model="input" style="width: 200px; margin-left: 10px" placeholder="" />
      </div>
      <div class="Filebox">
        <el-text class="mx-1">上传文件ZPI</el-text>
        <div class="w-200px">
          <el-upload ref="uploadRef" :limit="1" :on-change="changeFile" :auto-upload="false" :data="uploadfile">
            <template #trigger>
              <el-button size="small" type="primary">选取附件</el-button>
            </template>
            <el-button style="margin-left: 10px" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
          </el-upload>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="setMkdir()"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import WebCode from "@/components/Wbecode/webcode.vue";
import imgfile from "@/views/self/components/imgfile.vue";
import {
  Menu as IconMenu,
  Message,
  Document,
  Folder
} from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import {
  loadFIleList,
  mkdir,
  write,
  deleteFile,
  uploadFile,
  Compressfile,
  getDwonLink,
  UnZipFile
} from "@/api/worksheet";
import { message } from "@/utils/message";
import { typeFileRet, FileRetputh, Jsonfile, FileName } from "@/utils/fileType";
interface Tree {
  id: string;
  label: string;
  children?: Tree[];
}
// 动态图片
const imgcont = ref("dir");
// web子窗口
const webinfo = ref(null);
const router = useRouter();
const showWeb = ref(false);
const setFilebut = ref(false);
const setFile = ref(false);
const Savebut = ref(true);
const getKey = (prefix: string, id: number) => {
  return `${prefix}-${id}`;
};
const createData = (
  maxDeep: number,
  maxChildren: number,
  minNodesNumber: number,
  deep = 1,
  key = "node"
): Tree[] => {
  let id = 0;
  return Array.from({ length: minNodesNumber })
    .fill(deep)
    .map(() => {
      const childrenNumber =
        deep === maxDeep ? 0 : Math.round(Math.random() * maxChildren);
      const nodeKey = getKey(key, ++id);
      return {
        id: nodeKey,
        label: nodeKey,
        children: childrenNumber
          ? createData(maxDeep, maxChildren, childrenNumber, deep + 1, nodeKey)
          : undefined
      };
    });
};
const treeData = ref<any>([]);
onMounted(async () => {
  getWidth();
  treeData.value = await getFileList();
});

const outerVisible = ref(false);
const outer = () => {
  outerVisible.value = true;
};
// 获取屏幕大小
const infoWidth = ref(true);
const getWidth = () => {
  if (window.innerWidth < 800) {
    infoWidth.value = false;
  } else {
    infoWidth.value = true;
  }
};
// 数据提交
const nodetype = ref("");
const fileload = ref();
const butjudgment = ref(true);
const treeCurrentChange = (node, NodeObj) => {
  console.log("重复点击", node.label, NodeObj.data.value.type, NodeObj);
  showWeb.value = false;
  let parentNodes = getAllParentNodes(NodeObj, []);
  let path = node.label;
  if (parentNodes.length && NodeObj.data.value.type != "k") {
    delBut.value = false;
    parentNodes = parentNodes.slice(1);
    path = "/" + parentNodes.map(item => item.label).join("/");
    fileload.value = path;
    butjudgment.value = false;
  } else if (NodeObj.data.value.type == "k") {
    Savebut.value = true;
    nodetype.value = NodeObj.data.value.type;
    setFilebut.value = true;
    delBut.value = true;
    butjudgment.value = true;
  }
  if (NodeObj.data.value.type == "dir") {
    imgcont.value = "dir";
  } else {
    imgcont.value = typeFileRet(fileload.value);
  }
  webCodeinfo(NodeObj.data.value.type);
};
// 重置页面
const refreshPage = async () => {
  treeData.value = [];
  treeData.value = await getFileList();
};
// 创建文件或文件夹
const radio = ref("0");
const input = ref("");
const steFileinfo = () => {
  (radio.value = "0"), (input.value = "");
  setFile.value = true;
};
const setMkdir = async () => {
  if (input.value) {
    let path = "";
    if (!fileload.value) {
      path = input.value;
    } else {
      path = fileload.value + `/` + input.value;
    }
    if (radio.value == "1") {
      let res = await mkdir({
        path: path,
        container_id: router.currentRoute.value.query.container_id
      });
      console.log(res);
      if (res.data.code == 200) {
        message("创建成功", { type: "success" });
      }
      refreshPage();
      setFile.value = false;
    } else if (radio.value == "2") {
      setwrite(path);
      setFile.value = false;
    } else {
      message("请选择文件类型", { type: "error" });
    }
  } else {
    message("请输入文件名称", { type: "error" });
  }
};
// 创建文件夹
const setwrite = async path => {
  let res = await write({
    path: path,
    content: " ",
    container_id: router.currentRoute.value.query.container_id
  });
  if (res.data.code == 200) {
    refreshPage();
    message("创建成功", { type: "success" });
  }
};
// 上传
const uploadRef = ref(null); // 用于存储 el-upload 组件实例
const uploadfile = ref();
const files = ref({
  file: {}
});
const changeFile = uploadFile => {
  files.value.file = uploadFile;
  console.log(files.value.file);
};
const submitUpload = async () => {
  if (!files.value.file) {
    message("请选择文件后再上传", { type: "warning" });
    return;
  }
  let filepush = "";
  if (fileload.value) {
    filepush = fileload.value;
  } else {
    filepush = "";
  }
  console.log(filepush);
  await uploadFile({
    path: filepush,
    container_id: router.currentRoute.value.query.container_id,
    file: files.value.file.raw,
    filename: files.value.file.name
  }).then((res: any) => {
    if (res.data.code == 200) {
      refreshPage();
      setFile.value = false;
      uploadRef.value.clearFiles();
      files.value.file = {};
      message("上传成功", { type: "success" });
    }
  });
};

// 保存文件内容
const setwriteinfo = () => {
  webinfo.value.SetWriteInfo(
    fileload.value,
    router.currentRoute.value.query.container_id
  );
};
// 删除文件
const delBut = ref(true);
const FileDel = async () => {
  let res = await deleteFile({
    path: fileload.value,
    container_id: router.currentRoute.value.query.container_id
  });
  if (res.data.code == 200) {
    console.log(res);
    if (res.data.data.code != 500) {
      refreshPage();
      message("删除成功", { type: "success" });
      delBut.value = true;
      setFilebut.value = false;
    }
  }
};

// 调用webcode中的方法
const webCodeinfo = filetype => {
  if (filetype != "dir" && filetype != "k") {
    setFilebut.value = true;
    Savebut.value = false;
    if (showWeb.value) {
      preview();
    }
  } else if (filetype == "dir" && filetype != "k") {
    setFilebut.value = false;
    Savebut.value = true;
  }
};
// 在线预览
const onclickPreview = () => {
  showWeb.value = true;
  preview();
};
const preview = () => {
  console.log(
    "预览",
    fileload.value,
    router.currentRoute.value.query.container_id
  );
  webinfo.value.getFilinfo(
    fileload.value,
    router.currentRoute.value.query.container_id
  );
};
const getAllParentNodes = (treeNode, result = []) => {
  result.unshift(treeNode);
  if (treeNode.parent) {
    getAllParentNodes(treeNode.parent, result);
  }
  return result;
};
// 压缩文件
const Compress = async () => {
  console.log(FileRetputh(fileload.value), fileload.value);
  let res = await getFileList(fileload.value);
  console.log("ys", Jsonfile(fileload.value, res), res);
  await Compressfile({
    container_id: router.currentRoute.value.query.container_id,
    zip_name: fileload.value.substring(1) + ".zip",
    file_list: Jsonfile(fileload.value, res)
  }).then(res => {
    console.log(res);
    refreshPage();
  });
};
// 获取文件下载链接
const httpfile = async () => {
  console.log(fileload.value, FileName(fileload.value));
  await getDwonLink({
    path: fileload.value,
    container_id: router.currentRoute.value.query.container_id
  }).then(res => {
    if (res.data.data.code == 200) {
      let pushUrl = `${res.data.base_url}?filename=${FileName(fileload.value)}&downloadFileUuid=${res.data.data.data.downloadFileUuid}`;
      window.open(pushUrl);
    } else {
      massage("请选择文件而非文件夹", { type: "error" });
    }
  });
};
// 解压文件
const unzip = async () => {
  console.log(FileRetputh(fileload.value));
  await UnZipFile({
    container_id: router.currentRoute.value.query.container_id,
    zip_name: fileload.value.substring(1),
    output_dir: FileRetputh(fileload.value).substring(1)
  }).then(res => {
    console.log(res);
    if (res.data.code == 200) {
      massage("解压成功", { type: "success" });
      refreshPage();
    }
  });
};
const LazyLoadNode = async (node: Node, resolve: (data: Tree[]) => void) => {
  console.log("懒加载", node, node.level, fileload.value);
  console.log(imgcont.value);
  showWeb.value = false;
  if (fileload.value && nodetype.value != "k") {
    delBut.value = false;
    butjudgment.value = false;
  }
  if (node.level === 0) {
    return resolve(treeData.value);
  } else {
    if (node.data.value.type == "dir") {
      imgcont.value = "dir";
      let parentNodes = getAllParentNodes(node, []);
      let path = node.data.label;
      if (parentNodes.length) {
        parentNodes = parentNodes.slice(1);
        path = "/" + parentNodes.map(item => item.data.label).join("/");
      }
      const res = await getFileList(path);
      console.log(res);
      resolve(res);
    } else {
      resolve([]);
    }
  }
};

const infolist = ref([
  {
    label: "空",
    value: {
      type: "k"
    }
  }
]);
const getFileList = (path = "") => {
  return new Promise(async (resolve, reject) => {
    const { data } = await loadFIleList({
      container_id: router.currentRoute.value.query.container_id,
      path: path || ""
    });
    let res = [];
    if (data.data.code == 200) {
      const treeObj = data.data.data;
      res = Object.entries(treeObj).map(([key, value]) => {
        return {
          label: key,
          value: {
            ...value.info,
            type: value.type
          }
        };
      });
      if (!res[0]) {
        res = [
          {
            label: "空",
            value: {
              type: "k"
            }
          }
        ];
      }
    } else if (data.data.code == 500) {
      res = [
        {
          label: "无权限",
          value: {
            type: "k"
          }
        }
      ];
    }
    resolve(res);
  });
};
defineExpose({ outer });
</script>

<style lang="scss" scoped>
::v-deep .el-tree-node__content>.el-tree-node__expand-icon {
  position: absolute;
  opacity: 0;
}

::v-deep .el-tree-node__content {
  position: relative;
}

.Filebox {
  display: flex;
  flex-direction: row;
  align-items: baseline;
  justify-content: center;
  margin-bottom: 30px;

  .Filetext {
    display: flex;
    align-items: center;
    margin-right: 20px;
    text-align: center;
  }

  .Filename {
    display: flex;
    align-items: center;
    text-align: center;
  }
}

.mb-4 {
  padding-bottom: 5px;
}

.footer {
  position: absolute;
  bottom: 0;
  width: 200px;
  background: #fff;
}

.info {
  padding-bottom: 60px;
}

@media (max-width: 768px) {
  .vuewrap {
    flex-direction: column;
  }
}

.layout-container-demo .el-header {
  position: relative;
  color: var(--el-text-color-primary);
  background-color: var(--el-color-primary-light-7);
}

.layout-container-demo .el-aside {
  color: var(--el-text-color-primary);
  background: var(--el-color-primary-light-8);
}

.w-200px {
  width: 180px;
  margin-left: 20px;
}

.layout-container-demo .el-menu {
  border-right: none;
}

.layout-container-demo .el-main {
  padding: 0;
}

.layout-container-demo .toolbar {
  right: 20px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>
